package cn.ingenic.glasssync.camera;

import android.content.Context;
import android.util.Log;
import android.os.Handler;
import android.database.ContentObserver;
import android.net.Uri;
import android.content.Intent;
import android.provider.MediaStore;
import android.provider.Settings;
import cn.ingenic.glasssync.services.SyncData;
import cn.ingenic.glasssync.services.SyncModule;
import cn.ingenic.glasssync.services.SyncException;

public class PhotoModule extends SyncModule {
    private static final String PHOTO = "photo_module";
    private static final String TAG = "PhotoModule";
    private static final boolean DEBUG = true;
    private Context mContext = null;

    private static final String CAMERA_TYPE = "camera_type";
    private static final int TAKE_PHOTO = 1;
    private static final int RECORD = 2;
	private static final int CAMERA_STATE = 3;

    private static PhotoModule sInstance = null;
    private PhotoModule(Context context){
	super(PHOTO, context);
	mContext = context;

	Uri cameraStateUri = Settings.System.getUriFor("camera_state");
	mContext.getContentResolver().registerContentObserver(cameraStateUri,false,mContentObserver);

    }

    public static PhotoModule getInstance(Context c) {
	if (null == sInstance)
	    sInstance = new PhotoModule(c);
	return sInstance;
    }

    @Override
    protected void onCreate() {
    }

        private ContentObserver mContentObserver = new ContentObserver(new Handler()){
	     @Override
     	     public void onChange(boolean selfChange) {
		 super.onChange(selfChange);
		 if (DEBUG) Log.d(TAG, "contentObserver change");
	      	 sendCameraState();
	     }
       	};

    @Override
    protected void onRetrive(SyncData data) {
	int message = data.getInt(CAMERA_TYPE);
	if (DEBUG) Log.d(TAG, "onRetrive data"+message);
	switch (message) {
	case TAKE_PHOTO :
	    Intent intentCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
	    mContext.sendBroadcast(intentCapture);
	    break;
	case RECORD :
	    Intent stopRecord = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
	    mContext.sendBroadcast(stopRecord);
	    break;
	case CAMERA_STATE :
		sendCameraState();
		break;
    	default :
	    Log.e(TAG, "Unknow message " + message);
	    break;
	}
    }

	private void sendCameraState(){
		SyncData data = new SyncData();
		data.putInt("type", CAMERA_STATE);
		String state = "";
		try {
			state = Settings.System.getString(mContext.getContentResolver(),"camera_state");
			if (DEBUG) Log.d(TAG, "sendCameraState state="+state);
			data.putString("glass_camera_state", state);
			send(data);
		} catch (SyncException e) {
			Log.e(TAG, "sendCameraState : " + e);
		}
	}

}